package com.ljm.boot.retry.server;

import com.ljm.boot.retry.callback.CustomRecoveryCallback;
import com.ljm.boot.retry.callback.CustomRecoveryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@Service
public class RetryServer  {

    @Autowired
    private RetryTemplate retryTemplate;

    @Autowired
    private CustomRecoveryCallback customRecoveryCallback;

    @Retryable(value = {CustomRecoveryException.class, IOException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public void retryTest() throws CustomRecoveryException {
        log.info("retryTest,当前时间：{}",LocalDateTime.now());
        throw new CustomRecoveryException("test retry error");
    }

    public void retryTemplateTest() {
        //第一个参数是只需要执行的方法，第二个参数是降级处理方法
        retryTemplate.execute(f->function(),customRecoveryCallback);
    }

    /**
     * 具体的执行任务
     */
    public String function(){
        log.info("retryTemplateTest,当前时间：{}",LocalDateTime.now());
        throw new RuntimeException("test retry error");
    }

    @Recover
    public void fallback(Throwable throwable) {
        // 降级处理逻辑
        log.error("fallback,Error msg:{}",throwable.getMessage());
    }
}
